package com.iiot.redis;

import redis.clients.jedis.JedisCluster;
import redis.clients.util.JedisClusterCRC16;

import java.util.*;
import java.util.Map.Entry;

/**
 * @ClassName: RedisHelper @Description: REDIS相关的工具类
 */
public class RedisHelperList {
    /**
     * @param @param  jc
     * @param @param  keys
     * @param @return
     * @return List<String> 返回类型
     * @throws
     * @Title: mget @Description:
     */
    public static List<String> mget(JedisCluster jc, String... keys) {
        List<String> retList = null;
        Map<Integer, List<String>> slotMap = new HashMap<Integer, List<String>>();
        for (final String key : keys) {
            int slot = JedisClusterCRC16.getSlot(key);
            List<String> list = slotMap.get(slot);
            if (list == null) {
                slotMap.put(new Integer(slot), new LinkedList<String>() {
                    {
                        add(key);
                    }
                });
            } else {
                list.add(key);
            }
        }
        // 对于每一个都 调用mget
        Iterator<Entry<Integer, List<String>>> iter = slotMap.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<Integer, List<String>> entry = iter.next();
            String[] keyArray = new String[entry.getValue().size()];
            entry.getValue().toArray(keyArray);
            List<String> valueList = jc.mget(keyArray);
            if (retList == null) {
                retList = valueList;
            } else {
                retList.addAll(valueList);
            }
        }

        return retList;
    }
}
